<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\card\Dealer;
use app\common\model\Merchant;
use app\common\model\Merchantuser;
use app\common\model\Order;
use app\common\model\Washlog;
use Exception;
use think\Db;
use think\Validate;

/**
 * 提现接口
 */
class Withdrawal extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $type = 1;
    public function _initialize()
    {
        parent::_initialize();
        /*判断当前账号身份 start*/
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if(!in_array($token["type"],[1,2,3,4])) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        /*判断当前账号身份 end*/
        $this->type=$token["type"];
    }
    /**
     * 获取余额
     * */
    public function getMoney(){
        $user = $this->auth->getUser();
        if($this->type==1){
            if($user["is_trila"]==1){
                //飞狗平台
                $store=$user;
            }else{
                $store=Merchant::field("money")->where(["id"=>$user["merchant_id"]])->find();
            }
        }
        if($this->type==2){
            if($this->request->param("start_time") && !empty($this->request->param("start_time")))
            {
                $order = Order::field("sum(regionservice_commission) money")
                    ->where(["regionservice_id" => $user["regionservice_id"], "regionservice_status" =>'0'])
                    ->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")])
                    ->whereIn("status",['1','3'])
                    ->whereIn("type_data",['0','2'])
                    ->buildSql();
                $list=Washlog::field("sum(regionservice_commission) money")
                    ->where(["regionservice_id" => $user["regionservice_id"], "regionservice_status" =>'0'])
                    ->where("type_data <> '2'")
                    ->whereTime('createtime', 'between', [strtotime($this->request->param("start_time") . "00:00:00"), strtotime($this->request->param("end_time") . "23:59:59")])
                    ->union($order, true)
                    ->select();
                $moeny=0;
                if(!empty($list)){
                    $moeny=$list[0]["money"]+$list[1]["money"];
                }
                $store["money"]=$moeny;
            }else{
                $store=\app\common\model\Regionservice::field("money")->where(["id"=>$user["regionservice_id"]])->find();
            }
        }
        if($this->type==3){
            $store=Dealer::field("money")->where(["id"=>$this->auth->id])->find();
        }
        if($this->type==4){
            $store=\app\common\model\Distributor::field("money")->where(["id"=>$this->auth->id])->find();
        }
        $this->success("成功",$store["money"].'');
    }
    /**
     * 发起提现
     * */
    public function initiate(){
        $data=[
            ['type_data', 'require', '提现方式不能为空'],
            ['price', 'require', '提现金额不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if($params["type_data"]==1 && !$this->request->param("alipayAccount")) $this->error("请输入支付宝账号");
        $user = $this->auth->getUser();
        if($this->type==1){
            if($user["is_trila"]==1)
            {
                //飞狗平台
                $store=Merchantuser::get($this->auth->id);
            }else{
                $store=Merchant::where(["id"=>$user["merchant_id"]])->lock(true)->find();
            }
        }
        if($this->type==2){
            $store=\app\common\model\Regionservice::where(["id"=>$user["regionservice_id"]])->lock(true)->find();
        }
        if($this->type==3){
            $store=Dealer::where(["id"=>$this->auth->id])->lock(true)->find();
        }
        if($this->type==4){
            $store=\app\common\model\Distributor::where(["id"=>$this->auth->id])->lock(true)->find();
        }
        if(empty($store)) $this->error("账号不存在");
        if(in_array($this->type,[1,2])){
            if(!empty($store)){
                if(bcsub($store["money"],$params["price"])<0) $this->error("可提现余额不足");
            }else{
                $this->error("提现失败");
            }
            $params["store_id"]=$store["id"];
            if($user["is_trila"]==1){
                $params["is_trila"]=1;//飞狗平台
            }else{
                $params["account"]=$store["account_number"]??"";
                $params["account_image"]=$store["account_image"]??"";
            }
        }else{
            if($user["money"]<$params["price"]) $this->error("可提现余额不足");
            $params["account"]=$user["account_number"]??"";
            $params["account_image"]=$user["account_image"]??"";
        }
        $site=\think\Config::get('site');
        if($site["minimum_money"]>$params["price"]) $this->error("最低提现".$site["minimum_money"]."元");
        $model=new \app\common\model\Withdrawal();
        $today_price=$model->where(["user_id"=>$this->auth->id,"source_data"=>$this->type])
            ->whereTime('createtime', 'today')->sum("price");
        if($site["highest_money"]<$today_price || $site["highest_money"]<$today_price+$params["price"]) $this->error("当日最多提现".$site["highest_money"]."元");
        $params["source_data"]=$this->type;
        $params["commission"]= floor(($params["price"] * ($site["commission"]/100))*100)/100;//手续费
        $params["actual_receipt"]=$params["price"]-$params["commission"];//实际到账
        $params["user_id"]=$this->auth->id;
        $params["trans_no"]=$model->getTrans_no(20);
        Db::startTrans();
        try {
            $model->allowField(true)->save($params);
            $store->save(["money"=>$store["money"]-$params["price"]]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("成功");
    }
    /**
     * 提现列表
     * */
    public function list(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $params=$this->request->param();
        $user = $this->auth->getUser();
        $where=["user_id"=>$this->auth->id,"source_data"=>$this->type];
        if($this->type==0 && $user["is_trila"]==1){
            $where["is_trila"]=1;//飞狗平台
        }
        if(!isset($param["status"]) && $params["status"]!=3){
            $where["status"]=$this->request->param('status');
        }
        $list=\app\common\model\Withdrawal::field("id,status,price,commission,actual_receipt,remark,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,type_data")
            ->where($where)
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功",$list);
    }
}
